package com.azkj.album.view.activity;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.azkj.album.R;
import com.azkj.album.dto.AddOrderBean;
import com.azkj.album.dto.BackGroundListBean;
import com.azkj.album.dto.GalleryBean;
import com.azkj.album.dto.HistoryBean;
import com.azkj.album.dto.ListData;
import com.azkj.album.dto.MessageEvent;
import com.azkj.album.dto.MessageType;
import com.azkj.album.dto.NewGalleryBean;
import com.azkj.album.dto.NewPhotoBean;
import com.azkj.album.dto.VipCardBean;
import com.azkj.album.dto.VipInfoBean;
import com.azkj.album.network.ConfigStorage;
import com.azkj.album.network.utils.LogUtils;
import com.azkj.album.network.utils.ToastUtils;
import com.azkj.album.presenter.GetVIPInfoPresenter;
import com.azkj.album.presenter.NewPhotoPresenter;
import com.azkj.album.utils.SwipeLayout1111;
import com.azkj.album.utils.Utils;
import com.azkj.album.view.base.BaseActivity;
import com.azkj.album.view.iview.INewPhotoView;
import com.azkj.album.view.iview.IVipView;
import com.azkj.album.widget.DraggableCombinedImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;

import org.greenrobot.eventbus.EventBus;

import java.io.FileNotFoundException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class NewPhotoSynthesisActivity extends BaseActivity implements INewPhotoView, IVipView {
    //历史简介
    @BindView(R.id.tv_synthesis_list)
    TextView mTvSynthesisList;
    //备注简介
    @BindView(R.id.tv_synthesis_remake_list)
    TextView mTvSynthesisRemakeList;
    //截图布局
    @BindView(R.id.rl_synthesis_back_layout)
    RelativeLayout rl_synthesis_back_layout;
    //历史简介editText
    @BindView(R.id.et_synthesis_input_j)
    EditText et_input_history;
    //历史备注editText
    @BindView(R.id.et_synthesis_input_b)
    EditText et_input_remake;
    @BindView(R.id.tv_synthesis_input_j)
    TextView tv_synthesis_input_j;
    @BindView(R.id.tv_synthesis_input_b)
    TextView tv_synthesis_input_b;
    @BindView(R.id.ll_synthesis_styles_one)
    DraggableCombinedImageView ll_synthesis_styles_one;
    @BindView(R.id.ll_synthesis_3)
    DraggableCombinedImageView ll_synthesis_3;
    @BindView(R.id.ll_synthesis_styles_four)
    RelativeLayout ll_synthesis_styles_four;
    @BindView(R.id.ll_synthesis_styles_four_one)
    DraggableCombinedImageView ll_synthesis_styles_four_one;
    @BindView(R.id.ll_synthesis_styles_four_two)
    DraggableCombinedImageView ll_synthesis_styles_four_two;
    @BindView(R.id.ll_synthesis_styles_four_three)
    DraggableCombinedImageView ll_synthesis_styles_four_three;
    @BindView(R.id.ll_synthesis_styles_four_four)
    DraggableCombinedImageView ll_synthesis_styles_four_four;

    @BindView(R.id.ll_synthesis_styles_five)
    RelativeLayout ll_synthesis_styles_five;
    @BindView(R.id.ll_synthesis_styles_five_one)
    DraggableCombinedImageView ll_synthesis_styles_five_one;
    @BindView(R.id.ll_synthesis_styles_five_two)
    DraggableCombinedImageView ll_synthesis_styles_five_two;
    @BindView(R.id.ll_synthesis_styles_five_three)
    DraggableCombinedImageView ll_synthesis_styles_five_three;
    @BindView(R.id.ll_synthesis_styles_five_four)
    DraggableCombinedImageView ll_synthesis_styles_five_four;
    @BindView(R.id.ll_synthesis_styles_five_five)
    DraggableCombinedImageView ll_synthesis_styles_five_five;

    @BindView(R.id.ll_synthesis_styles_six)
    RelativeLayout ll_synthesis_styles_six;
    @BindView(R.id.ll_synthesis_styles_six_one)
    DraggableCombinedImageView ll_synthesis_styles_six_one;
    @BindView(R.id.ll_synthesis_styles_six_two)
    DraggableCombinedImageView ll_synthesis_styles_six_two;
    @BindView(R.id.ll_synthesis_styles_six_three)
    DraggableCombinedImageView ll_synthesis_styles_six_three;
    @BindView(R.id.ll_synthesis_styles_six_four)
    DraggableCombinedImageView ll_synthesis_styles_six_four;
    @BindView(R.id.ll_synthesis_styles_six_five)
    DraggableCombinedImageView ll_synthesis_styles_six_five;
    @BindView(R.id.ll_synthesis_styles_six_six)
    DraggableCombinedImageView ll_synthesis_styles_six_six;
    @BindView(R.id.ll_new_synthesis_tietu_layout)
    RelativeLayout ll_new_synthesis_tietu_layout;
    @BindView(R.id.iv_synthesis_tietu)
    ImageView iv_synthesis_tietu;
    @BindView(R.id.btn_sel)
    TextView btn_sel;
    @BindView(R.id.ll_title)
    View ll_title;
    @BindView(R.id.ll_synthesis_2)
    DraggableCombinedImageView ll_synthesis_2;
    @BindView(R.id.tv_synthesis_watermark)
    TextView tv_synthesis_watermark;
    @BindView(R.id.rl_bg)
    RelativeLayout rl_bg;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.tv_new_photo_synthesis_agin)
    TextView tv_new_photo_synthesis_agin;

    //贴图库
    private GalleryBean selGallery = new GalleryBean();
    private List<NewPhotoBean> newBackGround = new ArrayList<>();
    private List<String> backgroundName = new ArrayList<>();
    private ArrayList<String> imagesSelect = new ArrayList<>();
    private ArrayList<String> imagesAll = new ArrayList<>();

    private ArrayList<String> imagesFullSelect = new ArrayList<>();

    //新建图册选择的分类ID
    private Integer selectClassID;
    private Integer selectBackGroundID;
    private BackGroundListBean selectBackGroundBean;

    private NewPhotoPresenter mPresenter;
    private GetVIPInfoPresenter mPresenterVip;
    // 网络图片
    private ArrayList<NewGalleryBean> newGalleryBeanArrayList = new ArrayList<>();
    private String coverImgPath = "";
    private String choseImgPath = "";
    //封面网络图片
    private String mLoadUrl;
    private PopupWindow mPopWindow;
    // 跳转类型 1:新建图册 2:编辑图册
    private int mType;
    private ListData mListData;

    private int uploadSuccessCount = 0;
    private StringBuilder selectedFullAddress = new StringBuilder();

    private boolean isAnewSelect = false;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_new_photo_synthesis;
    }

    @Override
    public void initView() {
        Intent data = getIntent();
        mType = data.getIntExtra("type", 1);
        if (mType == 2) {
            mListData = (ListData) data.getSerializableExtra("detail");
            LogUtils.d(TAG + ":detail " + mListData.toString());
            tv_title.setText("编辑图册");
            tv_new_photo_synthesis_agin.setVisibility(View.VISIBLE);
            selectBackGroundBean = new BackGroundListBean();
            //选者的图片
            selectBackGroundBean.setImage(mListData.getBackgroundImage());

            // 用逗号分割的字符串转换为列表
            imagesFullSelect = new ArrayList<>(Arrays.asList(mListData.getChooseImages().split(",")));
            imagesSelect = new ArrayList<>();
            List<String> listSelect = Arrays.asList(mListData.getChooseImages().split(","));
            imagesSelect.addAll(listSelect);
            if (!mListData.getMapImage().equals("")) {
                selGallery = new GalleryBean();
                selGallery.setImage(mListData.getMapImage());
                selGallery.setId(String.valueOf(mListData.getMapId()));
                //贴图
                Glide.with((Context) this).load(mListData.getMapImage()).into(new SimpleTarget<Drawable>() {
                    @Override
                    public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                        iv_synthesis_tietu.setImageDrawable(resource);
                        btn_sel.setVisibility(View.GONE);
                        ll_new_synthesis_tietu_layout.setBackgroundResource(R.drawable.shape_tran_corner_3);
                    }
                });
            }
            //背景图
            if (!mListData.getBackgroundImage().equals("")) {
                //贴图
                Glide.with((Context) this).load(mListData.getBackgroundImage()).into(new SimpleTarget<Drawable>() {
                    @Override
                    public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
//                        rl_synthesis_back_layout.setBackground(resource);

                    }
                });
            }
            selectClassID = mListData.getCategoryId();
            selectBackGroundID = mListData.getBackgroundId();
            imagesAll = new ArrayList<>();
            List<String> listAll = Arrays.asList(mListData.getImages().split(","));
            imagesAll.addAll(listAll);
            et_input_history.setText(mListData.getIntro());
            et_input_remake.setText(mListData.getRemark());
        } else {
            imagesSelect = (ArrayList<String>) data.getSerializableExtra("imagesSelect");
            selectClassID = data.getIntExtra("selectClassID", 0);
            selectBackGroundID = data.getIntExtra("selectBackGroundID", 0);
            selectBackGroundBean = (BackGroundListBean) data.getSerializableExtra("selectBackGroundBean");
            imagesAll = (ArrayList<String>) data.getSerializableExtra("imagesAll");
            newGalleryBeanArrayList = new ArrayList<>(Collections.nCopies(imagesAll.size(), null));
            mListData = (ListData) data.getSerializableExtra("detail");
            if (mListData != null) {
                tv_title.setText("编辑图册");
                tv_new_photo_synthesis_agin.setVisibility(View.VISIBLE);
                if (!mListData.getMapImage().equals("")) {
                    //贴图
                    Glide.with((Context) this).load(mListData.getMapImage()).into(new SimpleTarget<Drawable>() {
                        @Override
                        public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                            iv_synthesis_tietu.setImageDrawable(resource);
                            btn_sel.setVisibility(View.GONE);
                            ll_new_synthesis_tietu_layout.setBackgroundResource(R.drawable.shape_tran_corner_3);
                        }
                    });
                }
                et_input_history.setText(mListData.getIntro());
                et_input_remake.setText(mListData.getRemark());
            }
        }

//        et_input_remake.setTextSize(TypedValue.COMPLEX_UNIT_PX, dpToPx(getApplicationContext(),10));
//        et_input_history.setTextSize(TypedValue.COMPLEX_UNIT_PX, dpToPx(getApplicationContext(),10));
        et_input_history.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                int lines = et_input_history.getLineCount();
                // 限制最大输入行数
                if (lines > 4) {
                    String str = editable.toString();
                    int cursorStart = et_input_history.getSelectionStart();
                    int cursorEnd = et_input_history.getSelectionEnd();
                    if (cursorStart == cursorEnd && cursorStart < str.length() && cursorStart >= 1) {
                        str = str.substring(0, cursorStart - 1) + str.substring(cursorStart);
                    } else {
                        str = str.substring(0, editable.length() - 1);
                    }
                    // setText会触发afterTextChanged的递归
                    et_input_history.setText(str);
                    // setSelection用的索引不能使用str.length()否则会越界
                    et_input_history.setSelection(et_input_history.getText().length());
                }
            }
        });
        et_input_remake.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                int lines = et_input_remake.getLineCount();
                // 限制最大输入行数
                if (lines > 3) {
                    String str = editable.toString();
                    int cursorStart = et_input_remake.getSelectionStart();
                    int cursorEnd = et_input_remake.getSelectionEnd();
                    if (cursorStart == cursorEnd && cursorStart < str.length() && cursorStart >= 1) {
                        str = str.substring(0, cursorStart - 1) + str.substring(cursorStart);
                    } else {
                        str = str.substring(0, editable.length() - 1);
                    }
                    // setText会触发afterTextChanged的递归
                    et_input_remake.setText(str);
                    // setSelection用的索引不能使用str.length()否则会越界
                    et_input_remake.setSelection(et_input_remake.getText().length());
                }
            }
        });

        showMiddleView();
    }

    public void showMiddleView() {
        // 隐藏所有view
        ll_synthesis_styles_one.setVisibility(View.GONE);
        ll_synthesis_2.setVisibility(View.GONE);
        ll_synthesis_3.setVisibility(View.GONE);
        ll_synthesis_styles_four.setVisibility(View.GONE);
        ll_synthesis_styles_five.setVisibility(View.GONE);
        ll_synthesis_styles_six.setVisibility(View.GONE);
        switch (imagesSelect.size()) {
            case 1:
                Log.d(TAG, "showMiddleView: " + imagesSelect.get(0));
                ll_synthesis_styles_one.setVisibility(View.VISIBLE);
                // 获取ll_synthesis_styles_one宽高
                ll_synthesis_styles_one.post(() -> {
                    int width = ll_synthesis_styles_one.getWidth();
                    int height = ll_synthesis_styles_one.getHeight();
                    Log.e("宽高", width + " " + height);
                    ll_synthesis_styles_one.setImages(new String[]{imagesSelect.get(0)}, width, height);
                });
                break;
            case 2:
                ll_synthesis_2.setVisibility(View.VISIBLE);
                // 获取ll_synthesis_2宽高
                ll_synthesis_2.post(() -> {
                    int width = ll_synthesis_2.getWidth();
                    int height = ll_synthesis_2.getHeight();
                    Log.e("宽高", width + " " + height);
                    ll_synthesis_2.setImages(imagesSelect.toArray(new String[0]), width, height);
                });

                break;
            case 3:
                ll_synthesis_3.setVisibility(View.VISIBLE);
                // 获取ll_synthesis_3宽高
                ll_synthesis_3.post(() -> {
                    int width = ll_synthesis_3.getWidth();
                    int height = ll_synthesis_3.getHeight();
                    Log.e("宽高", width + " " + height);
                    ll_synthesis_3.setImages(imagesSelect.toArray(new String[0]), width, height);

                });
                break;
            case 4:
                ll_synthesis_styles_four.setVisibility(View.VISIBLE);

                // 获取ll_synthesis_styles_four宽高
                ll_synthesis_styles_four_one.post(() -> {
                    int width = ll_synthesis_styles_four_one.getWidth();
                    int height = ll_synthesis_styles_four_one.getHeight();
                    Log.e("宽高", width + " " + height);
                    ll_synthesis_styles_four_one.setImages(new String[]{imagesSelect.get(0)}, width, height);
                });
                ll_synthesis_styles_four_two.post(() -> {
                    int width = ll_synthesis_styles_four_two.getWidth();
                    int height = ll_synthesis_styles_four_two.getHeight();
                    Log.e("宽高", width + " " + height);
                    ll_synthesis_styles_four_two.setImages(new String[]{imagesSelect.get(1)}, width, height);
                });
                ll_synthesis_styles_four_three.post(() -> {
                    int width = ll_synthesis_styles_four_three.getWidth();
                    int height = ll_synthesis_styles_four_three.getHeight();
                    Log.e("宽高", width + " " + height);
                    ll_synthesis_styles_four_three.setImages(new String[]{imagesSelect.get(2)}, width, height);
                });
                ll_synthesis_styles_four_four.post(() -> {
                    int width = ll_synthesis_styles_four_four.getWidth();
                    int height = ll_synthesis_styles_four_four.getHeight();
                    Log.e("宽高", width + " " + height);
                    ll_synthesis_styles_four_four.setImages(new String[]{imagesSelect.get(3)}, width, height);
                });
                break;
            case 5:
                ll_synthesis_styles_five.setVisibility(View.VISIBLE);
                // 获取ll_synthesis_styles_five宽高
                ll_synthesis_styles_five_one.post(() -> {
                    int width = ll_synthesis_styles_five_one.getWidth();
                    int height = ll_synthesis_styles_five_one.getHeight();
                    Log.e("宽高", width + " " + height);
                    ll_synthesis_styles_five_one.setImages(new String[]{imagesSelect.get(0)}, width, height);
                });
                ll_synthesis_styles_five_two.post(() -> {
                    int width = ll_synthesis_styles_five_two.getWidth();
                    int height = ll_synthesis_styles_five_two.getHeight();
                    Log.e("宽高", width + " " + height);
                    ll_synthesis_styles_five_two.setImages(new String[]{imagesSelect.get(1)}, width, height);
                });
                ll_synthesis_styles_five_three.post(() -> {
                    int width = ll_synthesis_styles_five_three.getWidth();
                    int height = ll_synthesis_styles_five_three.getHeight();
                    Log.e("宽高", width + " " + height);
                    ll_synthesis_styles_five_three.setImages(new String[]{imagesSelect.get(2)}, width, height);
                });
                ll_synthesis_styles_five_four.post(() -> {
                    int width = ll_synthesis_styles_five_four.getWidth();
                    int height = ll_synthesis_styles_five_four.getHeight();
                    Log.e("宽高", width + " " + height);
                    ll_synthesis_styles_five_four.setImages(new String[]{imagesSelect.get(3)}, width, height);
                });
                ll_synthesis_styles_five_five.post(() -> {
                    int width = ll_synthesis_styles_five_five.getWidth();
                    int height = ll_synthesis_styles_five_five.getHeight();
                    Log.e("宽高", width + " " + height);
                    ll_synthesis_styles_five_five.setImages(new String[]{imagesSelect.get(4)}, width, height);
                });
                break;
            case 6:
                ll_synthesis_styles_six.setVisibility(View.VISIBLE);
                // 获取ll_synthesis_styles_six宽高
                ll_synthesis_styles_six_one.post(() -> {
                    int width = ll_synthesis_styles_six_one.getWidth();
                    int height = ll_synthesis_styles_six_one.getHeight();
                    Log.e("宽高", width + " " + height);
                    ll_synthesis_styles_six_one.setImages(new String[]{imagesSelect.get(0)}, width, height);
                });
                ll_synthesis_styles_six_two.post(() -> {
                    int width = ll_synthesis_styles_six_two.getWidth();
                    int height = ll_synthesis_styles_six_two.getHeight();
                    Log.e("宽高", width + " " + height);
                    ll_synthesis_styles_six_two.setImages(new String[]{imagesSelect.get(1)}, width, height);
                });
                ll_synthesis_styles_six_three.post(() -> {
                    int width = ll_synthesis_styles_six_three.getWidth();
                    int height = ll_synthesis_styles_six_three.getHeight();
                    Log.e("宽高", width + " " + height);
                    ll_synthesis_styles_six_three.setImages(new String[]{imagesSelect.get(2)}, width, height);
                });
                ll_synthesis_styles_six_four.post(() -> {
                    int width = ll_synthesis_styles_six_four.getWidth();
                    int height = ll_synthesis_styles_six_four.getHeight();
                    Log.e("宽高", width + " " + height);
                    ll_synthesis_styles_six_four.setImages(new String[]{imagesSelect.get(3)}, width, height);
                });
                ll_synthesis_styles_six_five.post(() -> {
                    int width = ll_synthesis_styles_six_five.getWidth();
                    int height = ll_synthesis_styles_six_five.getHeight();
                    Log.e("宽高", width + " " + height);
                    ll_synthesis_styles_six_five.setImages(new String[]{imagesSelect.get(4)}, width, height);
                });
                ll_synthesis_styles_six_six.post(() -> {
                    int width = ll_synthesis_styles_six_six.getWidth();
                    int height = ll_synthesis_styles_six_six.getHeight();
                    Log.e("宽高", width + " " + height);
                    ll_synthesis_styles_six_six.setImages(new String[]{imagesSelect.get(5)}, width, height);
                });
                break;
        }
    }

    @Override
    public void initData() {
        Glide.with(this).load(selectBackGroundBean.getImage()).into(new SimpleTarget<Drawable>() {
            @Override
            public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
//                rl_synthesis_back_layout.setBackground(resource);
                rl_bg.setBackground(resource);
            }
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @OnClick({R.id.iv_back, R.id.tv_synthesis_list, R.id.tv_new_photo_synthesis_next, R.id.ll_new_synthesis_tietu_layout, R.id.tv_synthesis_remake_list, R.id.tv_new_photo_synthesis_agin})
    public void onClick(View v) {
        if (Utils.isFastClick()) return;
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_synthesis_list:
                mPresenter.selectIntro("1", "30", "");
                break;
            case R.id.tv_synthesis_remake_list:
                mPresenter.selectRemark("1", "30", "");
                break;
            case R.id.ll_new_synthesis_tietu_layout:
                //跳转贴图库
                Intent intent = new Intent(this, GallerySelActivity.class);
                startActivityForResult(intent, 100);
                break;
            case R.id.tv_new_photo_synthesis_next:
                aNewCompile();
                break;
            case R.id.tv_new_photo_synthesis_agin:
                Intent next = new Intent(this, NewPhotoSelectActivity.class);
                ArrayList<NewGalleryBean> newGalleryBeanArrayList = new ArrayList<>();
                String[] split = mListData.getImages().split(",");
                for (String s : split) {
                    NewGalleryBean newGalleryBean = new NewGalleryBean();
                    newGalleryBean.setFullUrl(s);
                    // 是否选择
                    if (isAnewSelect && !imagesFullSelect.isEmpty()) {
                        newGalleryBean.setSelect(imagesFullSelect.contains(s));
                    } else {
                        newGalleryBean.setSelect(imagesSelect.contains(s));
                    }
                    newGalleryBeanArrayList.add(newGalleryBean);
                }
                next.putExtra("gallerList", newGalleryBeanArrayList);
                next.putExtra("classID", selectClassID);
                // 携带type和detail
                next.putExtra("type", getIntent().getIntExtra("type", 2));
                next.putExtra("detail", getIntent().getSerializableExtra("detail"));
                startActivityForResult(next, 1002);
                break;
        }
    }

    private void aNewCompile() {
        showLoading("上传中...");
        // mPresenter.canAddOrder();
        runOnUiThread(() -> mPresenterVip.getVip());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (100 == requestCode && 100 == resultCode) {
            if (null != data) {
                btn_sel.setVisibility(View.GONE);
                ll_new_synthesis_tietu_layout.setBackgroundResource(R.drawable.shape_tran_corner_3);
                selGallery = (GalleryBean) data.getSerializableExtra("result");
                Glide.with(this).load(selGallery.getImage()).into(new SimpleTarget<Drawable>() {
                    @Override
                    public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                        iv_synthesis_tietu.setImageDrawable(resource);
                    }
                });
            }
        }
        if (RESULT_OK == resultCode) {
            if (1002 == requestCode) {
                isAnewSelect = true;
                imagesSelect = (ArrayList<String>) data.getSerializableExtra("imagesSelect");
                selectClassID = data.getIntExtra("selectClassID", 0);
                selectBackGroundID = data.getIntExtra("selectBackGroundID", 0);
                selectBackGroundBean = (BackGroundListBean) data.getSerializableExtra("selectBackGroundBean");
                imagesAll = (ArrayList<String>) data.getSerializableExtra("imagesAll");
                imagesFullSelect = (ArrayList<String>) data.getSerializableExtra("imagesFullSelect");


                initData();
                clearView();
                showMiddleView();
            }
        }
    }

    private void clearView() {
        ll_synthesis_styles_one.clearCanvas();
        ll_synthesis_2.clearCanvas();
        ll_synthesis_3.clearCanvas();
        ll_synthesis_styles_four_one.clearCanvas();
        ll_synthesis_styles_four_two.clearCanvas();
        ll_synthesis_styles_four_three.clearCanvas();
        ll_synthesis_styles_four_four.clearCanvas();
        ll_synthesis_styles_five_one.clearCanvas();
        ll_synthesis_styles_five_two.clearCanvas();
        ll_synthesis_styles_five_three.clearCanvas();
        ll_synthesis_styles_five_four.clearCanvas();
        ll_synthesis_styles_five_five.clearCanvas();
        ll_synthesis_styles_six_one.clearCanvas();
        ll_synthesis_styles_six_two.clearCanvas();
        ll_synthesis_styles_six_three.clearCanvas();
        ll_synthesis_styles_six_four.clearCanvas();
        ll_synthesis_styles_six_five.clearCanvas();
        ll_synthesis_styles_six_six.clearCanvas();

    }

    private void showPopupWindow(int type, List<String> historyList) {
        //设置contentView
        View contentView = LayoutInflater.from(this).inflate(R.layout.popupwindow_history_layout, null);
        mPopWindow = new PopupWindow(contentView, FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT, true);
        mPopWindow.setContentView(contentView);
        mPopWindow.setBackgroundDrawable(new ColorDrawable(0x7f000000));
        TextView cancle = contentView.findViewById(R.id.tv_serch_list_cancle);
        cancle.setOnClickListener(view -> mPopWindow.dismiss());
        //设置各个控件的点击响应
        LinearLayout listLayout = contentView.findViewById(R.id.ll_serch_list_layout);
        LayoutInflater li = LayoutInflater.from(this);
        //原始textView
        for (int i = 0; i < historyList.size(); i++) {
            View new_view = li.inflate(R.layout.popupwindow_item_history_layout, null, false);
            SwipeLayout1111 swipeLayout1111 = new_view.findViewById(R.id.ll_serch_list_swipe11);
            TextView number = new_view.findViewById(R.id.ll_serch_list_layout);
            number.setText(i + 1 + "");
            TextView name = new_view.findViewById(R.id.ll_serch_list_name);
            name.setText(historyList.get(i));
            TextView delete = new_view.findViewById(R.id.ll_serch_list_delete);
            delete.setOnClickListener(view -> {
                //获取到内容并删除
                String content = name.getText().toString();
                if (type == 1) {
                    mPresenter.deleteHistoryorIntro(content);
                } else {
                    mPresenter.deleteHistoryorRemake(content);
                }
                listLayout.removeView(new_view);
                swipeLayout1111.close();
            });
            int finalI = i;
            name.setOnClickListener(view -> {
                if (type == 1) {
                    et_input_history.setText(historyList.get(finalI));
                } else {
                    et_input_remake.setText(historyList.get(finalI));
                }
                mPopWindow.dismiss();
            });
            listLayout.addView(new_view);
        }
        //显示PopupWindow
        View rootview = LayoutInflater.from(this).inflate(R.layout.activity_new_photo_synthesis, null);
        mPopWindow.showAtLocation(rootview, Gravity.CENTER, 0, 0);

    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    private void savePhoto() {
        String token = ConfigStorage.getInstance().getToken();
        String etInputHistory = et_input_history.getText().toString().trim();
        StringBuilder imageUrl = new StringBuilder();
        if (mType == 2) {
            if (mListData != null) {
                imageUrl.append(mListData.getImages());
            }
        } else {
            for (NewGalleryBean newGalleryBean : newGalleryBeanArrayList) {
                imageUrl.append(newGalleryBean.getFullUrl()).append(",");
            }
            if (imageUrl.length() > 0) {
                imageUrl.deleteCharAt(imageUrl.length() - 1);
            }
        }

        //相册图片
        String choose = selectedFullAddress.toString();
        //备注
        String remark = et_input_remake.getText().toString().trim();
        String id;
        if (mListData != null) {
            id = String.valueOf(mListData.getId());
        } else {
            id = "0";
        }
        mPresenter.newSave(token, id, String.valueOf(selectClassID), String.valueOf(selectBackGroundID),
                selectBackGroundBean.getImage(), selGallery.getId(), selGallery.getImage(),
                imageUrl.toString(), choose, choseImgPath, etInputHistory, coverImgPath, remark);
    }

    /**
     * 该方式原理主要是：View组件显示的内容可以通过cache机制保存为bitmap
     */
    /**
     * scrollView转为Bitmap
     *
     * @param view
     * @return
     */
    public Bitmap getBitmapByView(View view) {
        // 测量视图及其内容
        view.measure(View.MeasureSpec.makeMeasureSpec(view.getWidth(), View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(view.getHeight(), View.MeasureSpec.EXACTLY));
        // 确定视图的布局位置
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
        // 创建相同大小的Bitmap
        Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
        // 利用Bitmap创建一个Canvas
        Canvas canvas = new Canvas(bitmap);
        // 绘制视图到Bitmap上
        view.draw(canvas);
        return bitmap;
    }


    public String saveImage29(Context context, Bitmap toBitmap) {
        //开始一个新的进程执行保存图片的操作
        String path = null;
        Uri insertUri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues());
        //使用use可以自动关闭流
        try {
            OutputStream outputStream = context.getContentResolver().openOutputStream(insertUri, "rw");
            if (toBitmap.compress(Bitmap.CompressFormat.JPEG, 90, outputStream)) {
                path = getRealPathFromUri(NewPhotoSynthesisActivity.this, insertUri);
                Log.e("保存", path + "success");
            } else {
                Log.e("保存", "fail");
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return path;
    }

    public static String getRealPathFromUri(Context context, Uri uri) {
        String filePath = "";
        String scheme = uri.getScheme();
        if (scheme == null) filePath = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            filePath = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            String[] proj = {MediaStore.Images.Media.DATA};
            Cursor cursor = context.getContentResolver().query(uri, proj, null, null, null);
            if (cursor != null) {
                if (cursor.moveToFirst()) {
                    int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    filePath = cursor.getString(columnIndex);
                }
                cursor.close();
            }
            if (TextUtils.isEmpty(filePath)) {
                filePath = getFilePathForNonMediaUri(context, uri);
            }
        }
        return filePath;
    }

    private static String getFilePathForNonMediaUri(Context context, Uri uri) {
        String filePath = "";
        Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                int columnIndex = cursor.getColumnIndexOrThrow("_data");
                filePath = cursor.getString(columnIndex);
            }
            cursor.close();
        }
        return filePath;
    }

    @Override
    protected void initPresenter() {
        mPresenter = new NewPhotoPresenter(this);
        mPresenterVip = new GetVIPInfoPresenter(this);
    }

    @Override
    public void classSuccess(List<NewPhotoBean> newPhotoBeans) {

    }

    @Override
    public void classFail(String msg) {

    }

    @Override
    public void uploadFileSuccess(int position, NewGalleryBean bean, boolean isCompile, int saveCount) {

        if (mType == 2) {
            hideLoading();
            if (!TextUtils.isEmpty(bean.getFullUrl())) {
                uploadSuccessCount++;
                Log.d(TAG, "uploadFileSuccess: isCoverImg === " + bean.isCoverImg());
                if (bean.isCoverImg()) {
                    coverImgPath = bean.getFullUrl();
                } else if (bean.isChoseImg()) {
                    choseImgPath = bean.getFullUrl();
                }
            } else {
                hideLoading();
                runOnUiThread(() -> ToastUtils.showCenterToast("上传图片失败"));
                return;
            }
            //包含封面图
            if (uploadSuccessCount == 2) {
                if (!imagesFullSelect.isEmpty()) {
                    for (String s : imagesFullSelect) {
                        selectedFullAddress.append(s).append(",");
                    }
                    if (selectedFullAddress.length() > 0) {
                        selectedFullAddress.deleteCharAt(selectedFullAddress.length() - 1);
                    }
                }
                savePhoto();
            }
        } else {
            if (!TextUtils.isEmpty(bean.getFullUrl())) {
                uploadSuccessCount++;
                Log.d(TAG, "uploadFileSuccess: isCoverImg === " + bean.isCoverImg());
                if (bean.isCoverImg()) {
                    coverImgPath = bean.getFullUrl();
                } else if (bean.isChoseImg()) {
                    choseImgPath = bean.getFullUrl();
                } else {
                    Log.d(TAG, "uploadFileSuccess: position" + position + " bean " + bean);
                    newGalleryBeanArrayList.set(position, bean);
                }
            } else {
                hideLoading();
                runOnUiThread(() -> ToastUtils.showCenterToast("上传图片失败"));
                return;
            }
            //包含封面图
            if (uploadSuccessCount == imagesAll.size() + 2) {
                for (NewGalleryBean newGalleryBean : newGalleryBeanArrayList) {
                    Log.d(TAG, "uploadFileSuccess: " + newGalleryBean.toString());
                    for (String s : imagesSelect) {
                        if (s.equals(newGalleryBean.getImgPath())) {
                            selectedFullAddress.append(newGalleryBean.getFullUrl()).append(",");
                        }
                    }
                }
                if (selectedFullAddress.length() > 0) {
                    selectedFullAddress.deleteCharAt(selectedFullAddress.length() - 1);
                }
                savePhoto();
            }
        }

    }

    @Override
    public void uploadFileFail(String msg) {
        hideLoading();
        ToastUtils.showCenterToast(msg);
    }

    @Override
    public void uploadProcess(int position, NewGalleryBean bean, boolean isCompile) {
    }

    @Override
    public void newSaveSuccess(String stringSave) {
        hideLoading();
        ToastUtils.showCenterToast("保存成功");
        EventBus.getDefault().post(new MessageEvent(MessageType.TYPE_ON_SAVE_SUCCESS, null));
        finish();
        LogUtils.d(TAG + ":save success " + stringSave);
    }

    @Override
    public void newSaveFail(String msg) {
        hideLoading();
        ToastUtils.showCenterToast(msg);
    }

    @Override
    public void backGroundSuccess(List<NewPhotoBean> stringBackGround) {
        for (int i = 0; i < stringBackGround.size(); i++) {
            backgroundName.add(stringBackGround.get(i).getName());
        }
        newBackGround.addAll(stringBackGround);
    }

    @Override
    public void backGroundFail(String msg) {

    }

    @Override
    public void backGroundListSuccess(List<BackGroundListBean> stringBackGround) {

    }

    @Override
    public void backGroundListFail(String msg) {

    }

    @Override
    public void introSuccess(List<String> stringHistoryList) {
        showPopupWindow(1, stringHistoryList);
    }

    @Override
    public void introFail(String msg) {

    }

    @Override
    public void remarkSuccess(List<String> stringRemarkList) {
        showPopupWindow(2, stringRemarkList);
    }

    @Override
    public void remarkFail(String msg) {

    }

    @Override
    public void addOrderSuccess(AddOrderBean addOrderBeans) {

    }

    @Override
    public void addOrderFail(String msg) {
        hideLoading();
        ToastUtils.showCenterToast(msg);
    }

    @Override
    public void getPerDetail(ListData listData) {

    }

    @Override
    public void getPerDetailFail(String msg) {

    }

    @Override
    public void VipSuccess(VipInfoBean vipInfoBean) {
        LogUtils.d(TAG + ":vip success " + vipInfoBean.getIs_vip());
        String token = ConfigStorage.getInstance().getToken();
        if (mType == 2) {
            upLoadCoverImg(token, vipInfoBean);
        } else {
            if (vipInfoBean.getAlbum_count() > 0) {
                //先上传图片都成功后请求接口
                uploadSuccessCount = 0;
                for (int i = 0; i < imagesAll.size(); i++) {
                    NewGalleryBean newGalleryBean = new NewGalleryBean();
                    newGalleryBean.setImgPath(imagesAll.get(i));
                    mPresenter.UploadFile(token, newGalleryBean, i);
                    if (imagesAll.size() - 1 == i) {
                        runOnUiThread(() -> {
                            upLoadCoverImg(token, vipInfoBean);
                        });
                    }
                }
            } else {
                hideLoading();
            }
        }
    }

    private void upLoadCoverImg(String token, VipInfoBean vipInfoBean) {
        if (TextUtils.isEmpty(selectBackGroundBean.getImage())) {
            ll_new_synthesis_tietu_layout.setVisibility(View.INVISIBLE);
        }
        if (selGallery == null || selGallery.getImage() == null) {
            ll_new_synthesis_tietu_layout.setVisibility(View.INVISIBLE);
        }
        // todo
        et_input_history.setVisibility(View.GONE);
        et_input_remake.setVisibility(View.GONE);
        mTvSynthesisRemakeList.setVisibility(View.GONE);
        if (vipInfoBean.getIs_vip() != 1) {
            tv_synthesis_watermark.setVisibility(View.VISIBLE);
        }
        tv_synthesis_input_j.setVisibility(View.VISIBLE);
        tv_synthesis_input_b.setVisibility(View.VISIBLE);
        tv_synthesis_input_j.setText(et_input_history.getText());
        tv_synthesis_input_b.setText(et_input_remake.getText());

        Bitmap cover = getBitmapByView(rl_bg);
        et_input_history.setVisibility(View.VISIBLE);
        et_input_remake.setVisibility(View.VISIBLE);
        mTvSynthesisRemakeList.setVisibility(View.VISIBLE);
        tv_synthesis_input_j.setVisibility(View.GONE);
        tv_synthesis_input_b.setVisibility(View.GONE);
        tv_synthesis_watermark.setVisibility(View.GONE);
        ll_new_synthesis_tietu_layout.setVisibility(View.VISIBLE);

        NewGalleryBean tempBea = new NewGalleryBean();
        tempBea.setCoverImg(true);
        tempBea.setBitmap(cover);
        mPresenter.UploadBitmap(tempBea, -1);

        // todo ,上传choose_image
        View ll_synthesis_styles_layout = findViewById(R.id.ll_synthesis_styles_layout);
        Bitmap bitmap = getBitmapByView(ll_synthesis_styles_layout);
        NewGalleryBean tempBea1 = new NewGalleryBean();
        tempBea1.setChoseImg(true);
        tempBea1.setBitmap(bitmap);
        mPresenter.UploadBitmap(tempBea1, -2);
    }

    @Override
    public void VipFail(String error) {
        hideLoading();
        ToastUtils.showCenterToast(error);
    }

    @Override
    public void deleteIntroSuccess(String sString) {

    }

    @Override
    public void deleteIntroFail(String error) {

    }

    @Override
    public void deleteRemarkSuccess(String sString) {

    }

    @Override
    public void deleteRemarkFail(String error) {

    }

    @Override
    public void MembershipRulesSuccess(String membershipRules) {

    }

    @Override
    public void MembershipRulesFail(String error) {

    }

    @Override
    public void VipCardSuccess(VipCardBean vipCardBean) {
    }

    @Override
    public void VipCardFail(String error) {
        ToastUtils.showCenterToast(error);
    }

    @Override
    public void HistorySuccess(List<HistoryBean> historyBeans) {

    }

    @Override
    public void HistoryFail(String error) {

    }

    public static float dpToPx(Context context, int dp) {
        return dp * context.getResources().getDisplayMetrics().density;
    }

}
